package com.example.llm.learn.api.intercept;

import com.example.llm.learn.api.dto.CommonResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthHandlerInterceptor implements HandlerInterceptor {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");
        if(StringUtils.hasText(authorization)){
            return Boolean.TRUE;
        }
        // 认证失败，直接写入 JSON 响应
        response.setContentType("application/json;charset=UTF-8");
        objectMapper.writeValue(response.getWriter(), CommonResponse.error401());
        return Boolean.FALSE;
    }
}
